package com.asohofrucol.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.asohofrucol.dto.AsohofrucolSessionDTO;
import com.asohofrucol.dto.AssistenceRegisterDTO;
import com.asohofrucol.dto.DealTechnicalAssistanceDTO;
import com.asohofrucol.dto.DealTechnicalAssistanceVisitDTO;
import com.asohofrucol.dto.RuatRegisterDTO;
import com.asohofrucol.service.DealTechnicalAssistanceService;
import com.asohofrucol.service.TechnicalAssistanceService;

public class AssistanceController {
	@Autowired
	private AsohofrucolSessionDTO aSession;
	@Autowired
	private TechnicalAssistanceService technicalAssistanceService;
	@Autowired
	private RuatDataController ruatDataController;
	@Autowired
	private DealTechnicalAssistanceService dealTechnicalAssistanceService;

	private RuatRegisterDTO selectedRuatRegister;

	private StreamedContent file;

	@Value("${assistence.image.pdf.files.path}")
	private String pdfFilesPath;

	public AssistanceController() {

	}

	public void viewOwnerData(ActionEvent actionEvent) {
		System.out.println("OwnerData");
		RequestContext context = RequestContext.getCurrentInstance();
		context.addCallbackParam("view", "owner_data.xhtml");
	}

	public void viewCropClassification(ActionEvent actionEvent) {
		System.out.println("viewPersonalData");
		RequestContext context = RequestContext.getCurrentInstance();
		context.addCallbackParam("view", "crop_classification.xhtml");
	}

	public void viewAssistance(ActionEvent actionEvent) {
		System.out.println("viewAssistance");
	}

	public void testLoadAssistance(ActionEvent actionEvent) {
		AssistenceRegisterDTO assistenceRegisterDTO = new AssistenceRegisterDTO();
		assistenceRegisterDTO.setVisitDataDTO(technicalAssistanceService
				.getTechniclaAssitanceVistData(1L));
		aSession.setSelectedAssistenceRegister(assistenceRegisterDTO);
	}

	public RuatRegisterDTO getSelectedRuatRegister() {
		return selectedRuatRegister;
	}

	public void setSelectedRuatRegister(RuatRegisterDTO selectedRuatRegister) {
		aSession.setSelectedRuatRegister(selectedRuatRegister);
		DealTechnicalAssistanceDTO dealTechnicalAssistanceDTO = dealTechnicalAssistanceService
				.getDealTechnicalAssistanceByRuatId(aSession
						.getSelectedRuatRegister().getId());

		List<DealTechnicalAssistanceVisitDTO> dealTechnicalAssistanceVisits = new ArrayList<DealTechnicalAssistanceVisitDTO>();
		if (dealTechnicalAssistanceDTO == null) {
			dealTechnicalAssistanceDTO = new DealTechnicalAssistanceDTO();
			dealTechnicalAssistanceDTO.setRuatId(aSession
					.getSelectedRuatRegister().getId());
			dealTechnicalAssistanceDTO.setStatus("1");
		} else {
			dealTechnicalAssistanceVisits = dealTechnicalAssistanceService
					.getDealTechnicalAssistanceVisitsByDealTechnicalAssistanceId(dealTechnicalAssistanceDTO
							.getId());
		}

		aSession.getSelectedDealAssistenceRegister().setRuatId(
				aSession.getSelectedRuatRegister().getId());
		aSession.getSelectedDealAssistenceRegister()
				.setDealTechnicalAssistance(dealTechnicalAssistanceDTO);
		aSession.getSelectedDealAssistenceRegister()
				.setDealTechnicalAssistanceVisits(dealTechnicalAssistanceVisits);
		ruatDataController.loadForestBusinessData();
		ruatDataController.loadAnimalBusinessData();
		ruatDataController.loadAgrarianBusinessData();
		ruatDataController.loadPriorityProduct();
		this.selectedRuatRegister = selectedRuatRegister;
	}

	public void saveSelectedDealAssistenceRegister(ActionEvent actionEvent) {
		dealTechnicalAssistanceService.saveDealAssistenceRegister(aSession
				.getSelectedDealAssistenceRegister(), aSession.getUserInfo()
				.getUserName());
	}

	public void saveDealAssistenceVisit(ActionEvent actionEvent) {
		// se guarda la visita y se actualiza el dto en sesion (que tengan los
		// ids)
		DealTechnicalAssistanceVisitDTO visitDTO = (DealTechnicalAssistanceVisitDTO) actionEvent
				.getComponent().getAttributes().get("visitDTO");
		dealTechnicalAssistanceService.saveDealAssistenceVisit(visitDTO,
				aSession.getUserInfo().getUserName());
		List<DealTechnicalAssistanceVisitDTO> dealTechnicalAssistanceVisits = dealTechnicalAssistanceService
				.getDealTechnicalAssistanceVisitsByDealTechnicalAssistanceId(visitDTO
						.getDealTechnicalAssistanceId());
		aSession.getSelectedDealAssistenceRegister()
				.setDealTechnicalAssistanceVisits(dealTechnicalAssistanceVisits);
		
		
		FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage("Guardado", "Información de visita guardada satisfactoriamente")); 
	}

	public void saveDealAssistence(ActionEvent actionEvent) {
		// se guarda la asistencia y se actualiza el dto (que tenga el id)
		dealTechnicalAssistanceService.saveDealAssistence(aSession
				.getSelectedDealAssistenceRegister()
				.getDealTechnicalAssistance(), aSession.getUserInfo()
				.getUserName());
		DealTechnicalAssistanceDTO dealTechnicalAssistanceDTO = dealTechnicalAssistanceService
				.getDealTechnicalAssistanceByRuatId(aSession
						.getSelectedRuatRegister().getId());
		aSession.getSelectedDealAssistenceRegister()
				.setDealTechnicalAssistance(dealTechnicalAssistanceDTO);
		
        FacesContext context = FacesContext.getCurrentInstance();  
        context.addMessage(null, new FacesMessage("Guardado", "Información general guardada satisfactoriamente"));  	
	}

	public void newDealAssistenceVisit(ActionEvent actionEvent) {
		DealTechnicalAssistanceVisitDTO visitDto = new DealTechnicalAssistanceVisitDTO();
		visitDto.setDealTechnicalAssistanceId(aSession
				.getSelectedDealAssistenceRegister()
				.getDealTechnicalAssistance().getId());
		visitDto.setPosition(aSession.getSelectedDealAssistenceRegister()
				.getDealTechnicalAssistanceVisits().size() + 1);
		visitDto.setFacilitatorUsername(aSession.getUserInfo().getUserName());
		visitDto.setStatus("1");
		aSession.getSelectedDealAssistenceRegister()
				.getDealTechnicalAssistanceVisits().add(visitDto);
 
	}

	public void handleFileUpload(FileUploadEvent event) {

		DealTechnicalAssistanceVisitDTO visitDTO = (DealTechnicalAssistanceVisitDTO) event
				.getComponent().getAttributes().get("visitDTO");
		System.out.println("llama al acion event  parametro " + visitDTO);
		System.out.println(event.getFile().getFileName());

		UploadedFile income = event.getFile();

		FileOutputStream out;
		String fileName ="";
		try {
			Date date = new Date();
			Calendar calendar = Calendar.getInstance();
			int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
			int year = calendar.get(Calendar.YEAR);
			fileName = year+"-"+dayOfYear+"-"+aSession.getSelectedRuatRegister().getIdType()
					+ "-" + aSession.getSelectedRuatRegister().getIdNumber()
					+ "-" + date.getTime() + ".pdf";
			out = new FileOutputStream(System.getenv(pdfFilesPath) + fileName);
			out.write(income.getContents());
			out.close();
			// se actualiza el DTO y se persiste el dato de nombre de archivo
			visitDTO.setEvidenceFileName(fileName);
			dealTechnicalAssistanceService.saveEvidenceFileName(visitDTO
					.getId(), fileName, aSession.getUserInfo().getUserName());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		FacesMessage msg = new FacesMessage("Guardado", "El archivo "+event.getFile()
				.getFileName() +" fué subido satisfactoriamente como "+fileName );
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public void initFile(ActionEvent actionEvent) {
		String filename = (String) actionEvent.getComponent().getAttributes()
				.get("filename");
		System.out.println("llama al acion event  parametro " + filename);
		DealTechnicalAssistanceVisitDTO visitDTO = (DealTechnicalAssistanceVisitDTO) actionEvent
				.getComponent().getAttributes().get("visitDTO");
		System.out.println("llama al acion event  parametro " + visitDTO);
		File filen = new File(System.getenv(pdfFilesPath) + filename);
		InputStream input;
		try {
			input = new FileInputStream(filen);

			ExternalContext externalContext = FacesContext.getCurrentInstance()
					.getExternalContext();
			setFile(new DefaultStreamedContent(input,
					externalContext.getMimeType(filen.getName()),
					filen.getName()));
			System.out.println("PREP = " + filen.getName());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

}
